/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.unix;

import java.net.InetAddress;
import java.net.UnknownHostException;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;

/**
 * This class provides implementation for 'unix_gethostbyaddr'
 * and 'unix_gethostbyname' primitives.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Gethost {

    /**
     * No instance of this class.
     */
    private Gethost() {
    } // end empty constructor

    /**
     * Constructs a host entry from an address.
     * @param ctxt context
     * @param addr host address
     * @return host entry corresponding to passed address
     * @throws Fail.Exception if address of host cannot be determined
     */
    @Primitive
    public static Value unix_gethostbyaddr(final CodeRunner ctxt,
                                           final Value addr)
        throws Fail.Exception {
        try {
            return createHost(ctxt, new InetAddress[] {
                                  InetAddress.getByAddress(addr.asBlock().getBytes())
                              });
        } catch (final UnknownHostException uhe) {
            Fail.raiseNotFound();
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'unix_gethostbyaddr(CodeRunner, Value)'

    /**
     * Constructs a host entry from a name.
     * @param ctxt context
     * @param name host name
     * @return host entry corresponding to passed address
     * @throws Fail.Exception if address of host cannot be determined
     */
    @Primitive
    public static Value unix_gethostbyname(final CodeRunner ctxt,
                                           final Value name)
        throws Fail.Exception {
        try {
            return createHost(ctxt, InetAddress.getAllByName(name.asBlock().asString()));
        } catch (final UnknownHostException uhe) {
            Fail.raiseNotFound();
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'unix_gethostbyname(CodeRunner, Value)'

    /**
     * Creates a host entry.
     * @param ctxt context
     * @param addr address to encapsulte into host entry
     * @return host entry
     */
    private static Value createHost(final CodeRunner ctxt,
                                    final InetAddress[] addr) {
        final int sz = addr.length;
        final Block addresses = Block.createBlock(sz, 0);
        for (int i = 0; i < sz; i++) {
            addresses.set(i, Value.createFromBlock(Block.createString(addr[i].getAddress())));
        } // end for
        final Block res = Block.createBlock(0,
                                            Value.createFromBlock(Block.createString(addr[0].getHostName())),
                                            ctxt.getContext().getAtom(0),
                                            addr[0].getAddress().length == 4 ? Value.ONE : Value.TWO,
                                            Value.createFromBlock(addresses));
        return Value.createFromBlock(res);
    } // end method 'createHost(CodeRunner, InetAddress)'

} // end class 'Gethost'
